﻿using System;
using System.Text;
using Bing.CodeGenerator.Core;

namespace Bing.CodeGenerator.Extensions
{
    /// <summary>
    /// 属性扩展
    /// </summary>
    public static class PropertyExtensions
    {
        /// <summary>
        /// 获取属性表达式字符串
        /// </summary>
        /// <param name="property">属性</param>
        public static string GetPropertyExpression(this Property property)
        {
            bool isString = property.SystemType == typeof(string);
            bool isByteArray = property.SystemType == typeof(byte[]);
            bool isDecimal = property.SystemType == typeof(Decimal);

            if (property.ColumnName.ToLower() == "isdeleted")
                return "            builder.HasQueryFilter( t => t.IsDeleted == false );\r\n";

            if (property.IsKey == false)
                return string.Empty;

            if (property.ColumnName.ToLower() == "version" && isByteArray)
                return string.Empty;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("            // " + property.Description);

            sb.Append(' ', 3 * 4);
            sb.Append("builder.Property(t => t.");
            if (property.IsPrimaryKey.SafeValue() && property.IsForeignKey.SafeValue() == false)
                sb.Append("Id");
            else
                sb.Append(property.PropertyName);
            sb.Append(")");

            sb.AppendLine();
            sb.Append(' ', 4 * 4);
            sb.Append(".HasColumnName(\"");
            sb.Append(property.ColumnName);
            sb.Append("\")");

            if (property.IsIdentity == true)
            {
                sb.AppendLine();
                sb.Append(' ', 4 * 4);
                sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
            }
            else if (property.IsAutoGenerated == true)
            {
                sb.AppendLine();
                sb.Append(' ', 4 * 4);
                sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)");
            }
            sb.AppendLine(";");

            return sb.ToString();
        }
    }
}
